<template>
  <div style="display: flex; flex-direction: column; align-items: center; gap: 30px;">
    <div style="width: 50%">
      <div class="card" style="padding: 30px">
        <el-form :model="data.user" label-width="100px" style="padding-right: 50px" :rules="passwordRules" ref="passwordForm">
          <el-form-item label="原密码" prop="password">
            <el-input v-model="data.user.password" show-password />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="data.user.newPassword" show-password />
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPasword">
            <el-input v-model="data.user.confirmPasword" show-password />
          </el-form-item>
          <div style="text-align: center">
            <el-button type="warning" @click="reset('password')">重置</el-button>
            <el-button type="primary" @click="savePassword">保存</el-button>

          </div>
        </el-form>
      </div>
    </div>

    <div class="user-profile-container">
      <div class="card user-profile-card">
        <div class="profile-picture-wrapper">
          <el-upload class="avatar-uploader" :show-file-list="false" :action="uploadUrl" :on-success="handleFileUpload">
            <img v-if="data.user.avatar" :src="data.user.avatar" class="avatar" alt="User Avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </div>
        <el-form :model="data.user" label-width="100px" class="user-form" :rules="passwordRules" ref="nameRef">
          <el-form-item label="账号" prop="userName" >
            <el-input v-model="data.user.username" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="data.user.name" autocomplete="off" />
          </el-form-item>
          <div class="form-actions">
            <el-button type="warning" @click="reset('user')">重置</el-button>
            <el-button type="primary" @click="saveUser">保存</el-button>

          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { updateInfoApi } from "@/utils/API/manager/UpdataInfo";
import { updatePasswordApi } from "@/utils/API/manager/Password";
import router from "@/router";

// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload';

const data = reactive({
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  form: {}
});

const passwordForm = ref(null);

// 自定义验证规则
const passwordRules = {
  password: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
  ],
  newPassword: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value === data.user.password) {
          callback(new Error('新密码不能与原密码相同'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPasword: [
    {
      required: true,
      message: '请确认新密码',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== data.user.newPassword) {
          callback(new Error('确认新密码与新密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  name: [
    { required: true, message: '请输入账号持有者姓名', trigger: 'blur' },
  ]
};

const handleFileUpload = (file) => {
  data.user.avatar = file.data;
};

const emit = defineEmits(["updateUser"]);
const nameRef =ref(null)
// 把当前修改的用户信息存储到后台数据库
const saveUser = () => {
  nameRef.value.validate(valid=>{
    if (valid) {
      updateInfoApi(data.user).then(res => {
        if (res.code === '200') {
          ElMessage.success('更新成功');
          // 把更新后的用户信息存储到缓存
          localStorage.setItem('system-user', JSON.stringify(data.user));
          emit('updateUser');
        } else {
          ElMessage.error(res.msg);
        }
      });
    }else{
      ElMessage.error('请填写必要数据');
    }
  })

};

// 把当前修改的用户账号和密码存储到后台数据库
const savePassword = () => {
  passwordForm.value.validate((valid) => {
    if (valid) {
      updatePasswordApi(data.user).then(res => {
        if (res.code === '200') {
          ElMessage.success('修改密码成功');
          // 把更新后的缓存删除，并且需要重新登录
          localStorage.removeItem('system-user');
          router.push('/login');
        } else {
          ElMessage.error(res.msg);
        }
      });
    } else {
      ElMessage.error('表单验证失败，请检查输入');
    }
  });
};

const reset = (type) => {
  if (type === 'user') {
    data.user.name = '';
  } else if (type === 'password') {
    data.user.newPassword = '';
    data.user.confirmPasword = '';
  }
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.join-seller-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  max-width: 400px;
  margin: 20px auto;
  text-align: center;
}

.card-header {
  margin-bottom: 15px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.card-body {
  padding: 10px 20px;
}

.card-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
}

.apply-button {
  width: 100%;
  max-width: 200px;
  border-radius: 4px;
  font-size: 16px;
  margin-top: 10px;
}

.user-profile-container {
  width: 50%;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.user-profile-card {
  padding: 30px;
  border: 1px solid #dcdcdc;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.profile-picture-wrapper {
  text-align: center;
  margin-bottom: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 24px;
  color: #999;
}

.user-form {
  padding-right: 50px;
}

.form-actions {
  text-align: center;
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
